package tt.dz.order.schedulingjob;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import tt.dz.order.pojo.AliPayCallBackRecord;
import tt.dz.order.pojo.OrderAccountingStatus;
import tt.dz.order.pojo.OrderInfo;
import tt.dz.order.pojo.OrderRefundStatus;
import tt.dz.order.util.AliPayUtil;
import tt.dz.order.util.OrderConstant.OrderPayChannelCode;
import tt.dz.order.util.OrderConstant.OrderStatus;
import tt.dz.order.util.UUIDUtil;
import tt.dz.order.util.XmlUtil;

/**
 * @Title 向支付宝发送充电预约退款请求的job
 * @author zhoutian   
 * @date 2015-11-17
 */
@Component
public class SendRefundingRequestToAliPayJob extends QuartzJobBean {
	private static Logger log = LoggerFactory.getLogger(SendRefundingRequestToAliPayJob.class);
	
	//截取的大小
	private int subSize = 50;

	@Override
	@SuppressWarnings("rawtypes")
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		//log.info("向支付宝发送充电预约退款请求,job start");
		List<String> refundOrderNos ;
		List<OrderRefundStatus> list ;
		try{
			list = OrderRefundStatus.getRefundInfoForSend(OrderPayChannelCode.alipay.value());
			if(list != null && !list.isEmpty()){
				//截取一部分（50个）充电预约退款订单发送
				List<OrderRefundStatus> subList  ;
				if(list.size() >= subSize){
					subList = list.subList(0, subSize);
					refundOrderNos = new ArrayList<String>(subSize);
				} else {
					subList = list;
					refundOrderNos = new ArrayList<String>(list.size());
				}
				for(OrderRefundStatus crs : subList){
					refundOrderNos.add(crs.getOrderNo());
				}
				//修改充电预约退款订单的状态为"正在发送"
				OrderRefundStatus.changeStatusToSending(refundOrderNos);
				//找出充电预约退款订单列表
				List<OrderInfo> refundOrderList = OrderInfo.getByIds(refundOrderNos);
				//key为充电预约订单号，value为充电预约退款订单
				Map<String, OrderInfo> refundOrderMap = new HashMap<String, OrderInfo>();
				List<String> chargeAppointmentOrderNos = new ArrayList<String>();
				for(OrderInfo refundOrder : refundOrderList){
					//充电预约退款订单的关联订单为充电预约订单
					String chargeAppointmentOrderNo = refundOrder.getRelatedOrderNo();
					chargeAppointmentOrderNos.add(chargeAppointmentOrderNo);
					refundOrderMap.put(chargeAppointmentOrderNo, refundOrder);
				}
				//找出充电预约订单支付回调记录
				List<AliPayCallBackRecord> aliPayCallBackRecords = AliPayCallBackRecord.getByIds(chargeAppointmentOrderNos);
				//要发送的参数
				Map<String, String> paramMap = new TreeMap<String, String>(
						new Comparator<String>(){
							@Override
							public int compare(String key1, String key2) {
								return key1.compareTo(key2);
							}
						}
				);
				List<String> needSendAgainOrderNos = new ArrayList<String>();
				List<String> successOrderNos = new ArrayList<String>();
				for(int i = 0 ; i < aliPayCallBackRecords.size(); i++){
					AliPayCallBackRecord aliPayCallBackRecord = aliPayCallBackRecords.get(i);
					String chargeAppointmentOrderNo = aliPayCallBackRecord.getOrderNo();
					OrderInfo refundOrder = refundOrderMap.get(chargeAppointmentOrderNo);
					String refundOrderNo = refundOrder.getOrderNo();
					String refundFeeForSend = refundOrder.getCaculatedTotalPrice().abs().toString();
					paramMap.put("service", "refund_fastpay_by_platform_nopwd");
					/*
					paramMap.put("partner", AliPayUtil.PARTNER);
					paramMap.put("_input_charset", AliPayUtil.INPUT_CHARSET);
					paramMap.put("sign_type", AliPayUtil.SIGN_TYPE);
					paramMap.put("seller_email", AliPayUtil.SELLER_EMAIL);
					paramMap.put("seller_user_id", AliPayUtil.SELLER_USER_ID);
					*/
					paramMap.put("refund_date", UUIDUtil.getCurrentDate(null, "yyyy-MM-dd hh:mm:ss"));
					//用退款单号作为批次号里的流水号部分
					paramMap.put("batch_no", new StringBuilder(UUIDUtil.getCurrentDate(null, "yyyyMMdd")).append(refundOrder.getOrderNo()).toString());
					paramMap.put("batch_num", "1");
					paramMap.put("detail_data", new StringBuilder(aliPayCallBackRecord.getTradeNo()).append("^").append(refundFeeForSend).append("^").append("充电预约部分退款").toString());
					String sign = AliPayUtil.sign(paramMap);
					paramMap.put("sign", sign);
					String retStr = AliPayUtil.sendRefundRequest(paramMap);				
					if(retStr == null || retStr.trim().length() == 0){
						needSendAgainOrderNos.add(refundOrder.getOrderNo());
					}else{
						Map<String, Object> retMap = XmlUtil.Xml2Map(retStr);
						Map retALiPayLabelMap = (Map) retMap.get("alipay");
						if(retALiPayLabelMap == null){
							needSendAgainOrderNos.add(refundOrderNo);
						}else{
							String retResult = (String) retALiPayLabelMap.get("is_success");
							if(retResult != null && retResult.equals("T")){
								successOrderNos.add(refundOrderNo);
							}
						}
					}
				}
				if(needSendAgainOrderNos.size() > 0){
					OrderRefundStatus.changeStatusToNeedSendAgain(needSendAgainOrderNos);
				}
				if(successOrderNos.size() > 0){
					OrderRefundStatus.changeStatusToSuccess(successOrderNos);
					OrderInfo.changeOrderStatus(successOrderNos, OrderStatus.payedDone.value());
					OrderAccountingStatus.batchSave(successOrderNos);
				}
			}
		} catch(Exception e){
			log.error("向支付宝发送充电预约退款请求出错", e);
		}
	}
}
